from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django.utils import timezone
from .models import RestRecord
from .serializers import RestRecordSerializer

class RestRecordViewSet(viewsets.ModelViewSet):
    serializer_class = RestRecordSerializer

    def get_queryset(self):
        qs = RestRecord.objects.all()
        p  = self.request.query_params

        # 1. 用户
        if p.get('user_id'):
            qs = qs.filter(user_id=p['user_id'])

        # 2. 休息类型
        if p.get('category'):
            qs = qs.filter(category=p['category'])

        # 3. 状态
        if p.get('flag'):
            qs = qs.filter(flag=p['flag'])

        # 4. 自定义日期范围（优先级高于 range=today/week）
        start_date = p.get('start_date')
        end_date   = p.get('end_date')
        if start_date and end_date:
            qs = qs.filter(start_time__date__range=[start_date, end_date])
        else:
            # 兼容旧的 range 参数
            time_range = p.get('range')
            if time_range == 'today':
                today = timezone.now().date()
                qs = qs.filter(created_at__date=today)
            elif time_range == 'week':
                qs = qs.filter(created_at__gte=timezone.now() - timezone.timedelta(days=7))

        return qs.order_by('-created_at')

    def perform_create(self, serializer):
        user_id = self.request.data.get('user_id')
        serializer.save(user_id=user_id)

    @action(detail=False, methods=['get'])
    def statistics(self, request):
        user_id = request.query_params.get('user_id')
        today = timezone.now().date()
        today_records = RestRecord.objects.filter(
            user_id=user_id,
            created_at__date=today
        )
        
        return Response({
            'today_count': today_records.count(),
            'total_duration': sum(r.duration for r in today_records),
            'completed_count': today_records.filter(flag='completed').count()
        }) 